package com.jvm123.excel.in.impl;

import com.jvm123.excel.in.FieldTypeBinder;

import static com.jvm123.excel.common.Constants.BASIC_TYPE_LIST;

public class DefaultFieldTypeBinder implements FieldTypeBinder {

    @Override
    public Object convertFieldType(Object value, Class<?> requiredType) {
        Object obj = null;
        String typeName = requiredType.getTypeName();
        String wrapperTypeName = getWrapperTypeName(typeName);
        Class<?> aClass = value.getClass();
        String valueTypeName = aClass.getTypeName();
        if (wrapperTypeName.equals(valueTypeName)) {
            // 包含了value为String或Date的类型
            obj = value;
        } else {
            if (value instanceof Double) {
                Number number = (Number) value;
                switch (wrapperTypeName) {
                    case "java.lang.Integer":
                        obj = number.intValue();
                        break;
                    case "java.lang.Float":
                        obj = number.floatValue();
                        break;
                    case "java.lang.Long":
                        obj = number.longValue();
                        break;
                    case "java.lang.Short":
                        obj = number.shortValue();
                        break;
                    case "java.lang.Byte":
                        obj = number.byteValue();
                        break;
                    case "java.lang.String":
                        obj = number.toString();
                        break;
                    default:
                        obj = null;
                }
            }
        }
        return obj;
    }

    private String getWrapperTypeName(String typeName) {
        String wrapperTypeName;
        int index = BASIC_TYPE_LIST.indexOf(typeName);
        if (index >= 8) {
            wrapperTypeName = BASIC_TYPE_LIST.get(index - 8);
        } else {
            wrapperTypeName = typeName;
        }
        return wrapperTypeName;
    }


}
